//! 自适应动态批处理系统

use std::collections::VecDeque;
use std::time::Duration;

/// 智能批处理控制器
pub struct DynamicBatcher {
    max_batch_size: usize,
    current_batch: usize,
    latency_history: VecDeque<Duration>,
}

impl DynamicBatcher {
    /// 创建新批处理器（初始批次大小建议设为4）
    pub fn new(initial_batch: usize) -> Self {
        Self {
            max_batch_size: 64, // 硬件限制最大批次
            current_batch: initial_batch,
            latency_history: VecDeque::with_capacity(10),
        }
    }

    /// 根据延迟动态调整批次大小
    pub fn adjust_batch_size(&mut self, latency: Duration) {
        self.latency_history.push_back(latency);
        if self.latency_history.len() > 10 {
            self.latency_history.pop_front();
        }

        let avg_latency = self.latency_history.iter().sum::<Duration>() 
            / self.latency_history.len() as u32;
        
        // 动态调整策略
        match avg_latency.as_millis() {
            0..=50 => self.current_batch = (self.current_batch * 2).min(self.max_batch_size),
            51..=200 => self.current_batch = self.current_batch,
            _ => self.current_batch = (self.current_batch / 2).max(1),
        }
    }

    /// 获取当前建议批次大小
    pub fn current_batch(&self) -> usize {
        self.current_batch
    }
}